#!/usr/bin/env python

from links_class import Links
import sys, os
import random

def init ( l, admin = 0 ):
	from liwe import parts

	l.layman.add_js ( "/modules/links/js/links.js" )

	if admin and int ( admin ):
		l.layman.add_js ( "/modules/links/js/links.admin.js" )

	return ''


def list_hp ( liwe, id_cnt ):
	res = ""
	id_cnt = int ( id_cnt )

	l = Links ( liwe )

	cnt = l.get_container ( id_cnt )

	res = '<span class="titolo">%s</span><br/>' % cnt [ 'name' ]

	def _set_links ( r ):
		if not r [ 'url' ].startswith ( 'http' ): r [ 'url' ] = "http://" + r [ 'url' ] 

		r [ '_target' ] = ''
		if r [ 'target' ]: r [ '_target' ] = 'target="_blank"'


	rows = l.list ( id_cnt )
	if rows:
		links = []
		c = 5
		for r in rows:
			if r [ 'sticky' ] == 0: break

			_set_links ( r )

			links.append ( '<a href="%s" class="lnk_testo" %s >%s</a><br />' % ( r [ 'url' ], r [ '_target' ], r [ 'testo' ] ) )

			c -= 1

			if c == 0: break

		dct_links = {}
		if c > 0:
			for x in range ( min ( c, len ( rows ) - ( 5 - c ) ) ):
				while 1:
					rand = random.randint ( 5 - c, len ( rows ) - 1  )

					if rand not in dct_links: break

				dct_links [ rand ] = 1

				r = rows [ rand ]
				_set_links ( r )
				links.append ( '<a href="%s" class="lnk_testo" %s >%s</a><br />' % ( r [ 'url' ], r [ '_target' ], r [ 'testo' ] ) )


		links = " ".join ( links )

		res += links

	return res
